// API service for communicating with the backend
const API_BASE_URL = 'http://localhost:8000/api';

export interface Asset {
  id: number;
  name: string;
  asset_number: string;
  status: string;
  host: number | null;
  host_info: {
    id: number;
    hostname: string;
    ip_address: string;
    status: string;
    assets_count: number;
    created_time: string;
  } | null;
  created_time: string;
  updated_time: string;
}

// 添加资产历史记录接口
export interface AssetHistory {
  id: number;
  asset: number;
  field_name: string;
  old_value: string | null;
  new_value: string | null;
  timestamp: string;
  user: string | null;
}

export interface Host {
  id: number;
  hostname: string;
  ip_address: string;
  status: string;
  assets_count: number;
  created_time: string;
}

export interface PaginatedResponse<T> {
  count: number;
  next: string | null;
  previous: string | null;
  results: T[];
}

// Assets API
export const getAssets = async (params?: Record<string, string>): Promise<PaginatedResponse<Asset>> => {
  const url = new URL(`${API_BASE_URL}/assets/assets/`);
  
  if (params) {
    Object.keys(params).forEach(key => {
      url.searchParams.append(key, params[key]);
    });
  }
  
  const response = await fetch(url.toString());
  if (!response.ok) {
    throw new Error(`Failed to fetch assets: ${response.statusText}`);
  }
  return response.json();
};

export const getAssetById = async (id: number): Promise<Asset> => {
  const response = await fetch(`${API_BASE_URL}/assets/assets/${id}/`);
  if (!response.ok) {
    throw new Error(`Failed to fetch asset: ${response.statusText}`);
  }
  return response.json();
};

export const getAsset = async (assetNumber: string): Promise<Asset> => {
  const response = await fetch(`${API_BASE_URL}/assets/assets/${assetNumber}/`);
  if (!response.ok) {
    throw new Error(`Failed to fetch asset: ${response.statusText}`);
  }
  return response.json();
};

// 添加获取资产变更历史的接口
export const getAssetHistory = async (assetNumber: string): Promise<AssetHistory[]> => {
  const response = await fetch(`${API_BASE_URL}/assets/assets/${assetNumber}/history/`);
  if (!response.ok) {
    throw new Error(`Failed to fetch asset history: ${response.statusText}`);
  }
  return response.json();
};

export const createAsset = async (asset: Omit<Asset, 'id' | 'created_time' | 'updated_time'>): Promise<Asset> => {
  const response = await fetch(`${API_BASE_URL}/assets/assets/`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(asset),
  });
  
  if (!response.ok) {
    throw new Error(`Failed to create asset: ${response.statusText}`);
  }
  return response.json();
};

export const updateAsset = async (assetNumber: string, asset: Partial<Omit<Asset, 'id' | 'asset_number' | 'created_time' | 'updated_time'>>): Promise<Asset> => {
  const response = await fetch(`${API_BASE_URL}/assets/assets/${assetNumber}/`, {
    method: 'PATCH',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(asset),
  });
  
  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Failed to update asset: ${response.status} ${response.statusText} - ${errorText}`);
  }
  return response.json();
};

export const deleteAsset = async (assetNumber: string): Promise<void> => {
  const response = await fetch(`${API_BASE_URL}/assets/${assetNumber}/`, {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    throw new Error('Failed to delete asset');
  }
};

// Hosts API
export const getHosts = async (params?: Record<string, string>): Promise<PaginatedResponse<Host>> => {
  const url = new URL(`${API_BASE_URL}/assets/hosts/`);
  
  if (params) {
    Object.keys(params).forEach(key => {
      url.searchParams.append(key, params[key]);
    });
  }
  
  const response = await fetch(url.toString());
  if (!response.ok) {
    throw new Error(`Failed to fetch hosts: ${response.statusText}`);
  }
  return response.json();
};

export const getHost = async (id: number): Promise<Host> => {
  const response = await fetch(`${API_BASE_URL}/assets/hosts/${id}/`);
  if (!response.ok) {
    throw new Error(`Failed to fetch host: ${response.statusText}`);
  }
  return response.json();
};

export const createHost = async (host: Omit<Host, 'id' | 'created_time' | 'assets_count'>): Promise<Host> => {
  const response = await fetch(`${API_BASE_URL}/assets/hosts/`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(host),
  });
  
  if (!response.ok) {
    throw new Error(`Failed to create host: ${response.statusText}`);
  }
  return response.json();
};

export const updateHost = async (id: number, host: Partial<Omit<Host, 'id' | 'created_time' | 'assets_count'>>): Promise<Host> => {
  const response = await fetch(`${API_BASE_URL}/assets/hosts/${id}/`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(host),
  });
  
  if (!response.ok) {
    throw new Error(`Failed to update host: ${response.statusText}`);
  }
  return response.json();
};

export const deleteHost = async (id: number): Promise<void> => {
  const response = await fetch(`${API_BASE_URL}/assets/hosts/${id}/`, {
    method: 'DELETE',
  });
  
  if (!response.ok) {
    throw new Error(`Failed to delete host: ${response.statusText}`);
  }
};